<?php
namespace app\applet\controller;

use app\applet\model\Applet as AppletModel;
use app\applet\model\Wechat as WechatModel;
use app\common\service\AppletService;
use nxcsoft\wechat\Driver;

/**
 * 授权回调接口
 */
class Auth extends \app\BaseController
{
    /**
     * 微信公众号授权
     */
    public function wechat($applet_id = 0)
    {
        $auth_code = empty ($_GET ['auth_code']) ? "" : trim($_GET ['auth_code']);    //获取授权码
        if (!empty($auth_code)) {
            $wx = new Driver;
            //获取授权信息
            if (!$auth = $wx->getAuth($auth_code)) {
                die(nxcsoft_json(['code' => 0, 'msg' => $wx->getError()]));
            }
            //获取授权应用的帐号基本信息
            if (!$result = $wx->getAppInfo($auth['authorizer_appid'])) {
                die(nxcsoft_json(['code' => 0, 'msg' => $wx->getError()]));
            }
            $app = $result['authorizer_info'];//得到授权应用的帐号基本信息
            if ($wechat = WechatModel::getWechat([
                'app_id' => $auth['authorizer_appid']
            ])) {
                die(nxcsoft_json(['code' => 0, 'msg' => '该公众号已存在，wechat_id:' . $wechat['wechat_id'] . '，请选择其它公众号完成授权绑定操作']));
            }
            if ($wechat = WechatModel::getWechat(['applet_id' => $applet_id])) {
                if (!empty($wechat['app_id']) && $wechat['app_id'] != $auth['authorizer_appid']) {
                    $wechat->clear($applet_id);//切换授权 - 清除历史数据
                }
            } else {
                $wechat = new WechatModel;
            }
            $wechat->save([
                'app_id' => $auth['authorizer_appid'],//授权方APPid
                'user_name' => $app['user_name'],//原始ID
                'app_name' => isset($app['nick_name']) ? $app['nick_name'] : '',    //昵称
                'head_img' => isset($app['head_img']) ? $app['head_img'] : '',//头像
                'qrcode_url' => $app['qrcode_url'],    //二维码地址
                'principal_name' => $app['principal_name'],    //主体名称
                'access_token' => $auth['authorizer_access_token'],    //令牌
                'expires_in' => time() + 7000,//令牌过期时间
                'authorizer_refresh_token' => $auth['authorizer_refresh_token'],//刷新令牌
                'applet_id' => $applet_id,
                'status' => 1    //是否授权
            ]);
            if ($applet_id > 0) {
                return redirect('/applet/wechat/index');
            }
            return redirect('/admin/wechat/index');
        }
        echo "error";
    }

    /**
     * @param int $applet_id
     * @return \think\response\Redirect
     * 微信小程序授权
     */
    public function wxapp($applet_id = 0)
    {
        //微信小程序授权
        $auth_code = empty ($_GET ['auth_code']) ? "" : trim($_GET ['auth_code']);    //获取授权码
        $error_msg = '';
        if (!empty($auth_code)) {
            $wx = new Driver;
            //获取授权信息
            if (!$auth = $wx->getAuth($auth_code)) {
                $error_msg = $wx->getError();
                echo $error_msg;die;
               //return message($error_msg, false);
            }
            $applet = AppletModel::getApplet(['app_id' => $auth['authorizer_appid']]);

            //验证是否重复授权小程序 如果授权绑定小程序了以后就不允许在绑定其他小程序了
            if ($applet && $applet['id'] != $applet_id) {
                $error_msg = '该小程序已存在，applet_id:' . $applet['id'] . '，请选择其它小程序完成授权绑定操作';
                echo $error_msg;die;
               //return message($error_msg, false);
//
            }
            $applet = AppletModel::get($applet_id);
            //获取授权应用的帐号基本信息
            if (!$result = $wx->getAppInfo($auth['authorizer_appid'])) {
                $error_msg = $wx->getError();
                echo $error_msg;die;
               //return message($error_msg, false);
            }
            $app = $result['authorizer_info'];//得到授权应用的帐号基本信息
            //如果已经进行了绑定，不允许切换
            if (!empty($applet['app_id']) && $applet['app_id'] != $auth['authorizer_appid']) {
                $error_msg = '不允许切换绑定其它小程序';
                echo $error_msg;die;
            }
            //添加服务器域名
            if (!$result = $wx->setServeDomain(0, '', $auth['authorizer_access_token'])) {
                $error_msg = $wx->getError();
               //return message($error_msg, false);

            }
            $api_domain = isset($result['apiurl']) ? $result['apiurl'] : '';
            //设置小程序简介
            if (!$result = $wx->setSignature(0, '', $auth['authorizer_access_token'])) {
                $error_msg = $wx->getError();
               //return message($error_msg, false);

            }
            $signature = isset($result['signature']) ? $result['signature'] : '';
            $saveData = [
                'app_name' => isset($app['nick_name']) ? $app['nick_name'] : '',    //昵称
                'head_img' => isset($app['head_img']) ? $app['head_img'] : '',        //头像
                'qrcode_url' => isset($app['qrcode_url']) ? $app['qrcode_url'] : '',    //二维码
                'user_name' => $app['user_name'],                    //原始ID
                'principal_name' => $app['principal_name'],            //主体名称
                'signature' => $signature,    //账号介绍
                'api_domain' => $api_domain,//服务器域名
                'error_msg' => $error_msg,//服务器域名
                'auth_status' => $app['service_type_info']['id'] == 0 ? 1 : 2,//小程序认证状态
                'app_id' => $auth['authorizer_appid'],                //授权方APPid
                'access_token' => $auth['authorizer_access_token'],    //令牌
                'expires_in' => time() + 7000,                        //令牌过期时间
                'authorizer_refresh_token' => $auth['authorizer_refresh_token'],    //刷新令牌
                'status' => 1,  //是否授权
                'id' => $applet_id    //是否授权
            ];
            $appletService = new  AppletService();
            $appletService->upInfo($saveData);
            // 保存授权状态
            return redirect('https://tp6.nxcsoft.top/nxcadmin/applet/applet');
        }
        echo "error";
    }
}
